import md5 from "md5"
import UserDao from "../dao/UserDao"
import ResultHelper from "../utils/ResultHelper"
import { plainToClass, plainToInstance } from "class-transformer"
import UserEntity from "../entities/UserEntity"

interface ILogin {
  account: string
  password: string
}

export default class UserService {

  static async login(data: ILogin) {
    if (!data.account) {
      const result = ResultHelper.error('请输入账号')
      return result
    }

    if (!data.password) {
      const result = ResultHelper.error('请输入密码')
      return result
    }

    const result = await UserDao.login(data.account, md5(data.password))

    if (JSON.stringify(result) !== "{}" && result) {
      return ResultHelper.success(result)
    } else {
      return ResultHelper.error("账号或密码错误")
    }


  }

  static async register(data: any) {
    if (!data.account || !data.password || !data.nickname) {
      return ResultHelper.error("账号或密码或昵称为空")
    }

    const User = plainToInstance(UserEntity, data)

    const errs = await User.validateThie()

    if (errs.length !== 0) {
      return ResultHelper.error(errs)
    }

    User.password = md5(User.password)

    const result = await UserDao.create(User)

    return ResultHelper.success(result)
  }

  static async getUserCount() {
    const result = await UserDao.getUserCount()
    return ResultHelper.success({
      count: result
    })
  }
}